// pages/shareMiddle/shareMiddle.js
const common = require("../../common/common.js").common;

var leader = require("../../common/leader.js").leader;

const app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        navData: [ {
            navTip: "秒杀",
            icon: "icon-lightningbshandian",
            backgroundStyle: "background:linear-gradient(90deg,rgba(34,206,46,1),rgba(49,193,45,1));",
            URL: "/pages/kill/kill"
        }, {
            navTip: "拼团",
            icon: "icon-jiageprice1",
            backgroundStyle: "background:linear-gradient(90deg,rgba(81,172,237,1),rgba(72,160,232,1));",
            URL: "/pages/assemble/assemble"
        }, {
            navTip: "砍价",
            icon: "icon-jifen1",
            backgroundStyle: "background:linear-gradient(90deg,rgba(242,201,59,1),rgba(245,194,67,1));",
            URL: ""
        }, {
            navTip: "任务",
            icon: "icon-renwuguanli-",
            backgroundStyle: "background:linear-gradient(90deg,rgba(255,82,176,1),rgba(254,47,159,1));",
            URL: ""
        } ],
        alert: 0,
        buy_count: 1,
        leaderChange: true,
        //团长切换弹窗显示隐藏，true隐藏
        currentLeaderInfo: {},
        //当前团长信息
        modalHide: true
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        let that = this;
        wx.hideShareMenu();
        if (options.scene) {
            var scene = decodeURIComponent(options.scene).split(":");
            that.setData({
                goodsId: scene[3],
                s_leader: scene[1]
            });
        }
        that.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        if (app.globalData.user) {
            //如果直接拿到openid
            that.setData({
                openid: app.globalData.user.openid
            });
            that.requestStart(app.globalData.user.openid);
        } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                that.setData({
                    openid: res.openid
                });
                that.requestStart(res.openid);
            });
        }
    },
    requestStart: function(openid) {
        let that = this;
        leader.getMyLeaderInfo_aync(that.data.openid, that.data.s_leader).then(() => {
            //需要leader_id才能有的模块
            that.getBase();
            that.getProInfo();
        });
    },
    /**
   * 跳转详情页
   */
    toDetail(e) {
        let that = this;
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: "/pages/pro_detail/pro_detail?id=" + id
        });
    },
    toFunction(e) {
        let that = this;
        var pageUrl = e.currentTarget.dataset.url;
        if (pageUrl) {
            wx.navigateTo({
                url: pageUrl
            });
        } else {
            wx.showToast({
                title: "此功能暂未开放",
                icon: "none"
            });
        }
    },
    /**
   * 获取商品信息
   */
    getProInfo() {
        var that = this;
        var id = that.data.goodsId;
        common.request({
            endpoint: "product/product_detail",
            method: "post",
            data: {
                id: id,
                visit_type: 1
            },
            success: res => {
                let details = res.extra;
                let custom_attributes_show = 0;
                for (var i = 0; i < details.custom_attributes.length; i++) {
                    if (details.custom_attributes[i]["show"] == 1) {
                        custom_attributes_show++;
                    }
                }
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = this.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = this.getProductBySku(details.sku, sku);
                that.setData({
                    custom_attributes_show: custom_attributes_show,
                    details: details,
                    sku: sku,
                    product_id: id,
                    sku_info: sku_info,
                    video_image: details.video_img,
                    video: details.video
                });
                wx.setNavigationBarTitle({
                    title: details.name
                });
                //获取推荐商品
                                that.getRecommendPro(res.extra.cid);
            }
        });
    },
    /**
   * 获取推荐商品
   */
    getRecommendPro: function(cid) {
        var that = this;
        var goodsId = that.data.goodsId;
        common.request({
            endpoint: "product/class_product",
            method: "post",
            data: {
                pid: cid
            },
            success: res => {
                var data = res.extra.sub ? res.extra.sub : [];
                that.setData({
                    goods: data
                });
            }
        });
    },
    /** 
   * 选择单个 sku 属性
   */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    /**
   * 根据 sku 获取物品
   */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    /** 
   * 重平衡 sku
   * key_id: integer
   */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /** 
   * 分割现有 sku 成对象数组
   */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /** 
   * 添加一个 sku
   */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /** 
   * 对选择的 sku 属性进行排序
   */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /** 
   * 重建 sku
   */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /**
   * 返回首页
   */
    goIndex() {
        wx.reLaunch({
            url: "/pages/index/index"
        });
    },
    //获取团长信息
    getMyLeaderInfo: function() {
        var that = this;
        var user = that.data.user;
        var user = that.data.user;
        common.request({
            endpoint: "leader/myleaderinfo",
            method: "post",
            data: {
                openid: user.openid
            },
            success: res => {
                this.setData({
                    myleaderinfo: res.extra
                });
                var uid = user.uid;
                var leaderid = that.data.options.my_leaderID;
                //路由获取的团长的用户id
                                var preLeaderId = res.extra.leader_id;
                this.setData({
                    uid: uid,
                    preLeaderId: preLeaderId
                });
                if (!!leaderid && uid != preLeaderId) {
                    if (!!leaderid && preLeaderId != leaderid && !!preLeaderId) {
                        // && !!res.extra.leader_id
                        common.request({
                            endpoint: "share/leader_info",
                            data: {
                                leader_id: leaderid
                            },
                            method: "post",
                            success(lres) {
                                //显示切换团长弹窗
                                that.setData({
                                    leaderChange: false,
                                    currentLeaderInfo: JSON.parse(lres).extra
                                });
                                if (!!preLeaderId) {
                                    //用户选过团长
                                    that.setData({
                                        pre_leader_show: false
                                    });
                                } else {
                                    //用户没有选过团长
                                    that.setData({
                                        pre_leader_show: true
                                    });
                                }
                            }
                        });
                    } else if (!!leaderid && preLeaderId != leaderid && !preLeaderId) {
                        common.request({
                            endpoint: "member/save_leader_id",
                            method: "post",
                            data: {
                                leader_id: leaderid,
                                openid: wx.getStorageSync("user").openid
                            },
                            success: res => {
                                //切换团长成功，保存团长信息，隐藏弹窗
                                that.setData({
                                    myleaderinfo: res.extra
                                });
                            }
                        });
                    } else {}
                } else if (!!leaderid && uid == res.extra.leader_id) {
                    //此用户自己是团长
                    if (leaderid != res.extra.leader_id) {
                        that.setData({
                            modalHide: false
                        });
                    } else {}
                } else {}
            }
        });
    },
    /**
   * 选择团长弹窗，选择团长
   */
    chooseButt(e) {
        var leaderid = e.detail.id;
        let that = this;
        if (leaderid != -1) {
            common.request({
                endpoint: "member/save_leader_id",
                method: "post",
                data: {
                    leader_id: leaderid,
                    openid: wx.getStorageSync("user").openid
                },
                success: res => {
                    //切换团长成功，保存团长信息，隐藏弹窗
                    that.setData({
                        leaderChange: true,
                        myleaderinfo: res.extra
                    });
                    wx.showToast({
                        title: "切换团长成功",
                        icon: "none"
                    });
                }
            });
        } else {
            that.setData({
                leaderChange: true
            });
        }
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    l_change: res.extra.l_change
                });
            }
        });
    }
});